<template>
    <ElSpace>
        <ElButton @click="$router.back()">返回上一页</ElButton>
        <ElButton type="success" :loading="loading" @click="getList">刷新</ElButton>
        <ElButton type="primary" :loading="loading" @click="openDialog({})">添加</ElButton>
    </ElSpace>
    <p></p>
    <Table v-valid="'usersAddressList'" :data="data" :cols="cols">
        <template v-slot:default="{ row }">
            {{ row.default ? '是' : '否' }}
        </template>
        <template #action="{ row }">
            <ElButton type="primary" @click="openDialog({ ...row })">修改</ElButton>
            <ElButton type="danger" @click="del(row)">删除</ElButton>
        </template>
    </Table>
    <DF labelWidth="130px" v-valid="['usersAddressAdd', 'usersAddressUpdate']" :model="address" :options="addUpdateOpts"
        ref="dialog" :title="address.id ? '修改用户地址' : '添加用户地址'" @ok="confirm" />
</template>

<script lang="ts" setup>
import { add, update, deleteAddress, getAll, IUserAddress, AddType, UpdateType, getPCD, IPCD } from '@/api/userAddress';
import { computed, ref, watch } from 'vue';
import ask from '@/components/Confirm';
import { valid } from '@/utils/common';
const { id } = defineProps({
    id: String
});

/**
 * loading
 */
const loading = ref(false);
/**
 * 数据
 */
const data = ref<IUserAddress[]>([]);
/**
 * dialog引用
 */
const dialog = ref();
/**
 * 用于修改的对象
 */
const address = ref(<AddType & UpdateType>{});
/**
 * 省市区
 */
const pcdList = ref(<IPCD>{});
/**
 * 添加修改表单配置项
 */
const addUpdateOpts = computed(() => ({
    zip_code: {
        title: '邮编',
        max: 6,
        required: true,
        rules: [{ min: 6 }]
    },
    phone: {
        title: '手机号',
        max: 11,
        required: true,
        rules: [{ pattern: /^1[3-9]\d{9}$/, message: '手机号格式错误' }]
    },
    province: {
        title: '省',
        tag: 'select',
        max: 6,
        required: true,
        values: pcdList.value.province?.map(({ province_code, province }) => ({ label: province, value: province_code })) ?? []
    },
    city: {
        title: '市',
        tag: 'select',
        max: 6,
        required: true,
        values: pcdList.value.city?.filter(c => c.p_code === address.value.province)?.map(({ city_code, city }) => ({ label: city, value: city_code })) ?? []
    },
    district: {
        title: '区',
        tag: 'select',
        max: 6,
        required: true,
        values: pcdList.value.area?.filter(c => c.p_code === address.value.city)?.map(({ area_code, area }) => ({ label: area, value: area_code })) ?? []
    },
    address: {
        title: '详细地址',
        max: 100,
        required: true,
    },
    default: {
        title: '是否为默认地址',
        tag: 'radio',
        required: true,
        values: [{ label: '是', value: true }, { label: '否', value: false }]
    }
}));
/**
 * 列
 */
const cols = {
    zip_code: {
        title: '邮编'
    },
    phone: {
        title: '手机号'
    },
    province_name: {
        title: '省'
    },
    city_name: {
        title: '市'
    },
    district_name: {
        title: '区'
    },
    address: {
        title: '详细地址'
    },
    default: {
        title: '是否为默认地址'
    },
    action: {
        title: '操作',
        width: 200
    }
}

/**
 * 提交
 * @param model 
 */
const confirm = async (model: AddType & UpdateType) => {
    try {
        if (model.id) {
            //@ts-ignore
            delete model.user_id;
        }
        else {
            model.user_id = id as any;
        }
        await (model.id ? update : add)({ ...model });
        dialog.value.hide();
        getList();
    } catch (error) {
        console.log(error);
    }
    dialog.value.stop();
}

watch(() => [address.value.province, address.value.city], ([newProvince, newCity], [oldProvince, oldCity]) => {
    if (oldProvince && newProvince !== oldProvince) {
        address.value.city = '';
    }
    else if (newCity !== oldCity && typeof oldCity !== 'undefined') {
        address.value.district = '';
    }
});

/**
 * 删除
 * @param param0 
 */
const del = async ({ id }: IUserAddress) => {
    let res: any;
    try {
        res = await ask(`您确定要删除吗？`);
        await deleteAddress(id);
        getList();
    } catch (error) { }
    res && res();
}

/**
 * 打开添加修改模态框
 * @param row 
 */
const openDialog = async (row: IUserAddress) => {
    try {
        //@ts-ignore
        delete row.province_name;
        //@ts-ignore
        delete row.city_name;
        //@ts-ignore
        delete row.district_name;
        address.value = row;
        dialog.value.show();
        if (!pcdList.value.province) {
            pcdList.value = await getPCD();
        }
    } catch (error) { }
}

/**
 * 搜索
 */
const getList = async () => {
    if (!valid('usersAddressList'))
        return;
    try {
        loading.value = true;
        const list = await getAll(id ?? '0');
        data.value = list;
    } catch (error) { }
    loading.value = false;
}

getList();
</script>

<style lang="scss" scoped></style>